package com.itheima.sfbx.insurance.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.framework.commons.utils.EmptyUtil;
import com.itheima.sfbx.framework.commons.utils.ExceptionsUtil;
import com.itheima.sfbx.insurance.constant.SafeguardCacheConstant;
import com.itheima.sfbx.insurance.dto.SafeguardVO;
import com.itheima.sfbx.insurance.enums.SafeguardEnum;
import com.itheima.sfbx.insurance.mapper.SafeguardMapper;
import com.itheima.sfbx.insurance.pojo.Safeguard;
import com.itheima.sfbx.insurance.service.ISafeguardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SafeguardServiceImpl extends ServiceImpl<SafeguardMapper, Safeguard> implements ISafeguardService {
    /**
     * 保障项多条件组合
     *
     * @param safeguardVO 保障项
     * @return queryWrapper查询条件
     */
    private QueryWrapper<Safeguard> queryWrapper(SafeguardVO safeguardVO) {
        QueryWrapper<Safeguard> queryWrapper = new QueryWrapper<>();
        //条例键查询
        if (!EmptyUtil.isNullOrEmpty(safeguardVO.getSafeguardKey())) {
            queryWrapper.lambda().eq(Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey());
        }
        //条例键名称查询
        if (!EmptyUtil.isNullOrEmpty(safeguardVO.getSafeguardKeyName())) {
            queryWrapper.lambda().eq(Safeguard::getSafeguardKeyName, safeguardVO.getSafeguardKeyName());
        }
        //条例键值查询
        if (!EmptyUtil.isNullOrEmpty(safeguardVO.getSafeguardVal())) {
            queryWrapper.lambda().eq(Safeguard::getSafeguardVal, safeguardVO.getSafeguardVal());
        }
        //排序查询
        if (!EmptyUtil.isNullOrEmpty(safeguardVO.getSortNo())) {
            queryWrapper.lambda().eq(Safeguard::getSortNo, safeguardVO.getSortNo());
        }
        //备注查询
        if (!EmptyUtil.isNullOrEmpty(safeguardVO.getRemake())) {
            queryWrapper.lambda().eq(Safeguard::getRemake, safeguardVO.getRemake());
        }
        //状态查询
        if (!EmptyUtil.isNullOrEmpty(safeguardVO.getDataState())) {
            queryWrapper.lambda().eq(Safeguard::getDataState, safeguardVO.getDataState());
        }
        //创建时间查询
        queryWrapper.lambda().orderByDesc(Safeguard::getCreateTime);
        return queryWrapper;
    }


    @Override
    @Cacheable(value = SafeguardCacheConstant.PAGE, key = "#pageNum+'-'+#pageSize+'-'+#safeguardVO.hashCode()")
    public Page<SafeguardVO> findPage(SafeguardVO safeguardVO, int pageNum, int pageSize) {
        try {
            //构建分页对象
            Page<Safeguard> safeguardPage = new Page<>(pageNum, pageSize);
            //构建查询条件
            QueryWrapper<Safeguard> queryWrapper = queryWrapper(safeguardVO);
            //执行分页查询
            Page<SafeguardVO> safeguardVOPage = BeanConv.toPage(page(safeguardPage, queryWrapper), SafeguardVO.class);
            //返回结果
            return safeguardVOPage;
        } catch (Exception e) {
            log.error("保障项分页查询异常：{}",ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.PAGE_FAIL);
        }
    }

    @Override
    public SafeguardVO findById(String safeguardId) {
        return null;
    }

    @Override
    public SafeguardVO save(SafeguardVO safeguardVO) {
        try {
            //转换为实体类
            Safeguard safeguard = BeanConv.toBean(safeguardVO, Safeguard.class);
            //保存数据，mp会将新增的id进行回填
            boolean flag = save(safeguard);
            if (!flag){
                throw new RuntimeException("保障项保存失败");
            }
        }catch (Exception e){
            log.error("保障项保存异常：{}",ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.SAVE_FAIL);
        }



        return null;
    }

    @Override
    public Boolean update(SafeguardVO safeguardVO) {
        try {
            //转换为实体类
            Safeguard safeguard = BeanConv.toBean(safeguardVO, Safeguard.class);
            boolean flag = updateById(safeguard);
            if (!flag){
                throw new RuntimeException("保障项更新失败");
            }
            return flag;
        }catch (Exception e){
            log.error("保障项更新异常：{}",ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
    }

    @Override
    public Boolean delete(String[] checkedIds) {
        try {
            //将字符串数组，转换为long数组
            List<Long> idList = Arrays.asList(checkedIds).stream().map(Long::valueOf).collect(Collectors.toList());
            boolean flag = removeByIds(idList);
            if (!flag){
                throw new RuntimeException("保障项删除失败");
            }
            //返回结果
            return flag;
        }catch (Exception e){
            log.error("保障项删除异常：{}",ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(SafeguardEnum.DEL_FAIL);
        }
    }

    @Override
    public List<SafeguardVO> findList(SafeguardVO safeguardVO) {
        try {
            //构建查询条件
            QueryWrapper<Safeguard> queryWrapper = queryWrapper(safeguardVO);
            //执行查询
            List<SafeguardVO> list = list(queryWrapper).stream().map(safeguard -> BeanConv.toBean(safeguard, SafeguardVO.class)).collect(Collectors.toList());
            //返回结果
            return list;
        } catch (Exception e) {
            log.error("保障项列表查询异常：{}",ExceptionsUtil.getStackTraceAsString(e));
        }
        return List.of();
    }

    @Override
    public List<SafeguardVO> findShowPageItemByKey(List<String> safeguardKeyList) {
        return List.of();
    }

    @Override
    public SafeguardVO findBySafeguardKey(String safeguardKey) {
        return null;
    }

    @Override
    public boolean saveBatch(Collection<Safeguard> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean saveOrUpdateBatch(Collection<Safeguard> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean updateBatchById(Collection<Safeguard> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean saveOrUpdate(Safeguard entity) {
        return false;
    }

    @Override
    public Safeguard getOne(Wrapper<Safeguard> queryWrapper, boolean throwEx) {
        return null;
    }

    @Override
    public Map<String, Object> getMap(Wrapper<Safeguard> queryWrapper) {
        return Map.of();
    }

    @Override
    public <V> V getObj(Wrapper<Safeguard> queryWrapper, Function<? super Object, V> mapper) {
        return null;
    }

//    @Override
//    public BaseMapper<Safeguard> getBaseMapper() {
//        return null;
//    }
}
